package org.springblade.modules.admin.service.parts.impl.strategy;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.entity.MaintainPartsWork;
import org.springblade.modules.admin.entity.MaintainPlanContent;
import org.springblade.modules.admin.enums.MaintainPlanContentEnum;
import org.springblade.modules.admin.enums.TaskStatusEnum;
import org.springblade.modules.admin.service.parts.AbstractOrderStateStrategy;
import org.springblade.modules.admin.vo.feishu.FeiShuFileInfoVO;
import org.springblade.modules.admin.vo.feishu.FeishuDownloadVO;
import org.springblade.modules.admin.vo.parts.PartsBaseInfoVO;
import org.springblade.modules.admin.vo.parts.PartsExecuteVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description 待采购策略实现 -> 对应状态11
 * @Author ysq
 * @Date 2024/05/16
 **/
@Slf4j
@Service(value = "procurementOrderStrategy")
public class ProcurementOrderStrategyImpl extends AbstractOrderStateStrategy {
	@Transactional(rollbackFor = Exception.class)
	@Override
	public Object handle(PartsExecuteVO executeParams) {
		log.info("=============配件工单-状态流转-待采购，时间:[{}]，参数：[{}]============", DateUtil.now(), executeParams);
		// 状态变更
		MaintainPlanContent updatePlanContent = new MaintainPlanContent();
		updatePlanContent.setId(executeParams.getPlanId());
		updatePlanContent.setStatus(executeParams.getTargetStatus());
		boolean planRes = maintainPlanContentService.updateById(updatePlanContent);

		// 同步飞书-实际销售单价(含税)/元、实际销售总额(含税)/元、报价单回签附件
		MaintainPartsWork maintainPartsWork = maintainPartsWorkService.getByPlanId(executeParams.getPlanId());
		if (Func.isNull(maintainPartsWork)) {
			log.error("配件工单明细不存在, 工单id：[{}]", executeParams.getPlanId());
			return R.status(false);
		}
		PartsBaseInfoVO partsBaseInfo = JSONObject.parseObject(maintainPartsWork.getPartsInfo(), PartsBaseInfoVO.class);
		if (partsBaseInfo == null) {
			partsBaseInfo = new PartsBaseInfoVO();
		}
		partsBaseInfo.setSalePrice(String.valueOf(executeParams.getExt().get("salePrice")));
		partsBaseInfo.setTotalSales(String.valueOf(executeParams.getExt().get("totalSales")));
		List<Map<String, String>> quotationReplyFiles = null;
		try {
			quotationReplyFiles = partsFileHandler(executeParams);
		} catch (Exception e) {
			log.error(e.getMessage());
			return R.status(false);
		}
		partsBaseInfo.setQuotationReplyFiles(quotationReplyFiles);
		maintainPartsWork.setPartsInfo(JSONObject.toJSONString(partsBaseInfo));
		boolean partsRes = maintainPartsWorkService.updateById(maintainPartsWork);
		if (!planRes || !partsRes) {
			log.error("状态流转失败, 工单id：[{}]", executeParams.getPlanId());
			return R.status(false);
		}

		return R.data(TaskStatusEnum.getTaskName(MaintainPlanContentEnum.MAINTAIN_PARTS.getId(), executeParams.getTargetStatus()));
	}

	@Override
	public void after(PartsExecuteVO executeParams) {
		// 插入任务追踪日志
		maintainMalfunctionLogService.insertWorkLog(executeParams.getPlanId(),
			TaskStatusEnum.valueOf(executeParams.getEvent()).getName(),
			TaskStatusEnum.valueOf(executeParams.getEvent()).getStatus(),
			null,
			AuthUtil.getUserId(),
			"采购");
	}

	/**
	 * 同步飞书配件信息-报价单附件
	 * @param executeParams 执行参数
	 * @return 附件地址
	 */
	private List<Map<String, String>> partsFileHandler(PartsExecuteVO executeParams) {
		String fieldName = "报价单回签附件";
		List<Map<String, String>> fileUrls = new ArrayList<>();
		JSONArray fileArr = null;
		try {
			String recordDataJson = feiShuUtil.getBitableRecord(executeParams.getAppToken(), executeParams.getTableId(), executeParams.getRecordId());
			fileArr = JSONObject.parseObject(recordDataJson).getJSONObject("record").getJSONObject("fields").getJSONArray(fieldName);
		} catch (Exception e) {
			throw new ServiceException("状态流转-获取检索记录失败，参数：" + executeParams.toString());
		}

		if (Func.hasEmpty(executeParams.getExt(), fileArr)) {
			return fileUrls;
		}
		FeiShuFileInfoVO fileInfo = Func.toBean(executeParams.getExt(), FeiShuFileInfoVO.class);
		if (Func.isEmpty(fileInfo)) {
			return fileUrls;
		}

		// 处理附件
		List<FeishuDownloadVO> downloadParams = new ArrayList<>();
		if (Func.equalsSafe(fileInfo.getFieldName(), fieldName)) {
			List<String> files = Func.toStrList(fileInfo.getFileIds());
			for (int j = 0; j < files.size(); j++) {
				JSONObject fileItemObj = fileArr.getJSONObject(j);
				FeishuDownloadVO downloadParam = new FeishuDownloadVO();
				downloadParam.setFileToken(fileItemObj.getString("file_token"));
				String extra = String.format("{\"bitablePerm\":{\"tableId\":\"%s\",\"attachments\":{\"%s\":{\"%s\":[\"%s\"]}}}}",
					executeParams.getTableId(), fileInfo.getFieldId(), executeParams.getRecordId(), fileItemObj.getString("file_token"));
				downloadParam.setExtra(extra);
				downloadParams.add(downloadParam);
			}
		}
		if (!downloadParams.isEmpty()) {
			try {
				fileUrls = feiShuUtil.download(downloadParams);
			} catch (Exception e) {
				throw new ServiceException("状态流转-拉取飞书素材失败，参数：" + downloadParams);
			}
		}
		return fileUrls;
	}
}
